import os
import re

# # 读取OCR规则文件
# ocr_file_path = 'd:/workspace/cfop-random/oll_ocr.txt'
# image_dir = 'D:/魔方/cut_cfop_oll'
# output_text_path = 'd:/workspace/cfop-random/renamed_files_oll.txt'

# 读取OCR规则文件
ocr_file_path = 'd:/workspace/cfop-random/pll_ocr.txt'
image_dir = 'D:/魔方/cut_cfop_pll'
output_text_path = 'd:/workspace/cfop-random/renamed_files_pll.txt'

# 读取OCR规则文件
# ocr_file_path = 'd:/workspace/cfop-random/f2l_ocr.txt'
# image_dir = 'D:/魔方/cut_cfop_f2l'
# output_text_path = 'd:/workspace/cfop-random/renamed_files_f2l.txt'

# 存储重命名规则和公式的字典
rename_rules = {}
formula_data = {}

# 读取并解析OCR文件
with open(ocr_file_path, 'r', encoding='utf-8') as f:
    content = f.read()

# 使用正则表达式匹配所有图片块
pattern = r'>>>>识别图片:(.*?)<<<<\n(.*?)\n((?:.*?\n)*?)(?=>>>>|$)'
matches = re.findall(pattern, content, re.DOTALL)

for match in matches:
    original_filename = match[0].strip()
    new_filename = match[1].strip()
    formula_lines = [line.strip() for line in match[2].strip().split('\n') if line.strip()]
    formula_text = '<br/>'.join(formula_lines)

    if original_filename and new_filename:
        rename_rules[original_filename] = new_filename
        formula_data[new_filename] = formula_text

# 重命名图片文件并生成输出文本
with open(output_text_path, 'w', encoding='utf-8') as output_file:
    # 遍历图片目录
    for filename in os.listdir(image_dir):
        if filename.lower().endswith('.png') and filename in rename_rules:
            new_name = rename_rules[filename] + '.png'
            old_path = os.path.join(image_dir, filename)
            new_path = os.path.join(image_dir, new_name)

            # 重命名文件
            os.rename(old_path, new_path)
            print(f'重命名: {filename} -> {new_name}')

            # 写入公式文本
            if new_name[:-4] in formula_data:
                output_file.write(f'{new_name[:-4]}.png: {formula_data[new_name[:-4]]}\n')

print(f'重命名完成，共处理 {len(rename_rules)} 个文件')
print(f'公式文本已保存至: {output_text_path}')